package com.qs.order.service.impl;


import com.qs.order.dataobject.OrderDetail;
import com.qs.order.dataobject.OrderMaster;
import com.qs.order.dto.OrderDto;
import com.qs.order.enums.OrderStatusEnum;
import com.qs.order.enums.PayStatusEnum;
import com.qs.order.enums.ResultEnum;
import com.qs.order.exception.OrderException;
import com.qs.order.repository.OrderDetailRepository;
import com.qs.order.repository.OrderMasterRepository;
import com.qs.order.service.OrderDetailService;
import com.qs.order.utils.KeyUtil;
import com.qs.product.client.ProductClient;
import com.qs.product.common.DecreaseStockInput;
import com.qs.product.common.ProductInfoOutput;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Desc:  订单商品serviceImpl
 * @author: jianfeng
 * @Time: 2019/9/12 10:13
 */

@Service
public class OrderDetailServiceImpl implements OrderDetailService {

    @Autowired
    private OrderDetailRepository detailRepository;

    @Autowired
    private OrderMasterRepository masterRepository;

    @Autowired
    private ProductClient productClient;

    @Override
    @Transactional
    public OrderDto create(OrderDto dto) {

        //生成orderId
        String orderId=KeyUtil.genUniqueKey();

        //查询商品信息（调用商品服务）
        List<String> productIdList =dto.getOrderDetailList().stream()
                .map(OrderDetail::getProductId)
                .collect(Collectors.toList());

        List<ProductInfoOutput> productInfoOutputList=productClient.listForOrder(productIdList);

        //计算总价

        BigDecimal orderAmout=new BigDecimal(BigInteger.ZERO);//声明一个总价，初始化为0

        for (OrderDetail orderDetail:dto.getOrderDetailList()){
            for (ProductInfoOutput productInfoOutput:productInfoOutputList){
                if (productInfoOutput.getProductId().equals(orderDetail.getProductId())){
                    //单价*数量,BigDecimal类型的 “*” 是multiply方法，最后面还要累加所以要用add方法
                    orderAmout=productInfoOutput.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity())).add(orderAmout);
                    BeanUtils.copyProperties(productInfoOutput,orderDetail);
                    orderDetail.setOrderId(orderId);
                    orderDetail.setDetailId(KeyUtil.genUniqueKey());
                    orderDetail.setCreateTime(new Date());
                    orderDetail.setUpdateTime(new Date());
                    //订单详情入库
                    detailRepository.save(orderDetail);

                }
            }
        }

        //扣库存（调用商品服务）
        List<DecreaseStockInput> decreaseStockInputList=dto.getOrderDetailList().stream()
                .map(e -> new DecreaseStockInput(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
        productClient.decreaseStock(decreaseStockInputList);

        //订单入库
        OrderMaster orderMaster=new OrderMaster();
        //先dto设置orderId
        dto.setOrderId(orderId);
        BeanUtils.copyProperties(dto,orderMaster);
        orderMaster.setOrderAmount(orderAmout);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMaster.setCreateTime(new Date());
        orderMaster.setUpdateTime(new Date());

        masterRepository.save(orderMaster);

        return dto;
    }

    @Override
    @Transactional
    public OrderDto finish(String orderId) {
        //1.先查询订单
        Optional<OrderMaster> orderMasterOptional =masterRepository.findById(orderId);
        if (!orderMasterOptional.isPresent()){
            throw new OrderException(ResultEnum.ORDER_NOT_EXIST);
        }

        //2.判断订单状态
        OrderMaster orderMaster=orderMasterOptional.get();
        if (!OrderStatusEnum.NEW.getCode().equals(orderMaster.getOrderStatus())){
            throw new OrderException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //3.修改订单状态为完结
        orderMaster.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        masterRepository.save(orderMaster);

        //4.查询订单详情
        List<OrderDetail> orderDetailList=detailRepository.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)){
            throw new OrderException(ResultEnum.ORDER_DETAIL_NOT_EXIST);
        }
        OrderDto orderDto=new OrderDto();
        BeanUtils.copyProperties(orderMaster,orderDto);
        orderDto.setOrderDetailList(orderDetailList);

        return orderDto;
    }
}
